package cn.appsys.controller.backend;

import cn.appsys.pojo.BackendUser;
import cn.appsys.service.backend.BackendUserService;
import cn.appsys.service.developer.DataDictionaryService;
import cn.appsys.tools.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/back")
public class BackendUserController {
    @Resource
    private BackendUserService backendUserService;
    @Resource
    private DataDictionaryService dataDictionaryService;

    private Logger logger = Logger.getLogger(BackendUserController.class);

    @RequestMapping(value = "/login")
    public String login(){
        logger.debug("login==========");
        return "backendlogin";
    }

    @RequestMapping(value = "/dologin")
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword,
                          HttpSession session, HttpServletRequest request) throws Exception {
        BackendUser backendUser = null;
        backendUser = backendUserService.login(userCode,userPassword);

        if(backendUser != null){
            String userTypeName = dataDictionaryService.getValueNameByValueId(backendUser.getUserType(),"用户类型");
            backendUser.setUserTypeName(userTypeName);
            session.setAttribute(Constants.USER_SESSION,backendUser);
            return "redirect:/back/flatform/main";
        }else {
            request.setAttribute("error","用户名或密码不正确");
            return "backendlogin";
        }
    }

    @RequestMapping(value = "/flatform/main")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/back/login";
        }
        return "backend/main";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "backendlogin";
    }
}
